# coding:utf-8
from __future__ import division
import argparse
import datetime
import os
import sys
import re
import pysequoiadb
from pysequoiadb import client
from pysequoiadb.error import SDBBaseError,InvalidParameter
import pysequoiadb

flags = argparse.ArgumentParser()
# flags.add_argument("--ip",type=str,required=True,help="addr of ip")
flags.add_argument("--dir",type=str,default="/data/log",help="dir of log")
flags.add_argument("--sdb_ip",default='10.244.171.142',type=str,help='ip of sdb')
args = flags.parse_args()

sdb_ip = args.sdb_ip
sdb_port = "11810"
sdb_user = "peter"
sdb_password = "Foxconn99."
collection_space = "monitor"
collection_name = "processlog"

# cl.create_index({"ip":1},"ipindex",True,True)

def get_face_log(cl=None,dir=args.dir,log_prefix="redis_face"):
    os.chdir(dir)
    logs = []
    for log in os.listdir(os.getcwd()):
        if log.startswith(log_prefix):
            logs.append(log)
    for log in logs:
        with open(log,'r') as fi:
            print(log)
            pattern = re.compile("running mtcnn detection time:\s(.*?)\s"
                                 "running facenet and resnet time:\s(.*?)\s"
                                 "label=\[\'(.*?)\'\],channel=(\d+),distance=\[(.*?)\],stime=\[\'(.*?)\'\],\s"
                                 "runnig time:\s(.*?)\s"
                                 "(.*)\s")
            results = re.findall(pattern,fi.read())
            print(len(results))
            for result in results:
                # print result
                tmp={"mtcnn_dc":result[0],
                     "run_frnet":result[1],
                     "label":result[2],
                     "channel":result[3],
                     "distance":result[4],
                     "stime":result[5],
                     "run_time":result[6],
                     "etime":result[-1]}

                try:
                    cl.insert(tmp)
                except InvalidParameter as e:
                    print("插入出错")
                    print(e.detail)


def main():
    try:
        db = client(sdb_ip,sdb_port,sdb_user,sdb_password)
    except SDBBaseError as e:
        pysequoiadb._print(e)
        print("连接出错 请校验")
        sys.exit(0)
    cs = db.get_collection_space(collection_space)
    try:
        cl = cs.get_collection(collection_name)
    except SDBBaseError as e:
        cl = cs.create_collection(collection_name,{'ShardingKey':{"_id":1},
                                                       'ShardingType':"hash",
                                                       'Partition':65536,
                                                       'ReplSize':1,
                                                       'Compressed':True,
                                                       'AutoSplit':True})


    timezone = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(timezone)
    get_face_log(cl)


if __name__ == "__main__":
    main()